package com.huluobo.jetpackdemo.coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.huluobo.jetpackdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitActivity : AppCompatActivity() {
    private val retrofit = Retrofit.Builder().baseUrl("http://10.161.9.80:7012")
        .addConverterFactory(GsonConverterFactory.create()).build()

    private val apiService = retrofit.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_retrofit)

//        apiService.loadBanner().enqueue(object : Callback<BannerBeanResult> {
//            override fun onResponse(call: Call<BannerBeanResult>, response: Response<BannerBeanResult>) {
//                val bannerBeanResult = response.body()
//                Log.i("TagA", "banner:$bannerBeanResult")
//            }
//
//            override fun onFailure(call: Call<BannerBeanResult>, t: Throwable) {
//                Log.i("TagA", "failed:${t.message}")
//            }
//        })

        //2.8以上可以直接在主线程请求
        val job = Job()
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = apiService.loadBanner2()
            val tv = findViewById<TextView>(R.id.tv)
            tv.text = result.toString()
        }

        //Retrofit2.8以下,需要切换线程
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            val result = withContext(Dispatchers.IO) {
//                apiService.loadBanner2()
//            }
//            val tv = findViewById<TextView>(R.id.tv)
//            tv.text = result.toString()
//        }
    }
}